const { contextBridge, ipcRenderer } = require('electron');

// 暴露 ipcRenderer 到渲染进程
contextBridge.exposeInMainWorld('ipc', {
    send: (channel, data) => ipcRenderer.send(channel, data),
    on: (channel, func) => {
        // 确保回调函数接收到正确的参数
        ipcRenderer.on(channel, (event, ...args) => {
            try {
                func(event, ...args); // 将参数传递给回调函数
            } catch (error) {
                console.error(`Error in IPC handler for channel "${channel}":`, error);
                console.error(`args for channel "${channel}":`, ...args);
            }
        });
    },
    once: (channel, func) => {
        // 确保回调函数接收到正确的参数
        ipcRenderer.once(channel, (event, ...args) => {
            try {
                func(event, ...args); // 将参数传递给回调函数
            } catch (error) {
                console.error(`Error in IPC handler for channel "${channel}":`, error);
                console.error(`args for channel "${channel}":`, ...args);
            }
        });
    },

    invoke: (channel, data) => ipcRenderer.invoke(channel, data),
    removeAllListeners: (channel) => ipcRenderer.removeAllListeners(channel),
    off: (channel, func) => {
        // 移除指定 channel 的监听器
        ipcRenderer.off(channel, func);
    },
    // 获取客户端的地址
    getNetworkInfo: () => ipcRenderer.invoke('get-network-info'),
    getHostName: () => ipcRenderer.invoke('get-computer-name'),
});